package com.wq.code;

import java.util.concurrent.TimeUnit;

/**
 * @Author: wangqiang20995
 * @Date:2019/5/23
 * @Description:
 * @Resource:
 */
public class ThreadInterrupt {

    public static void main(String[] args){

        InnerRunnable innerRunnable = new InnerRunnable(new Object());
        Thread thread = new Thread(innerRunnable);
        thread.start();

        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            System.out.println("main 线程休眠时被中断...");
        }

//        wakeUpByNotify(innerRunnable);
        wakeUpByInterrupt(thread);

    }

    private static void wakeUpByInterrupt(Thread thread){
        System.out.println("main线程中断子线程");
        InnerRunnable.interrupt(thread);
    }

    private static void wakeUpByNotify(InnerRunnable innerRunnable) {
        System.out.println("main线程开始唤醒子线程...");
        innerRunnable.wakeUp();
    }

    private static class InnerRunnable implements Runnable{

        private final Object monitor;

        public InnerRunnable(Object monitor){
            this.monitor = monitor;
        }


        public void wakeUp(){
            synchronized (monitor){
                System.out.println("Thread:" + Thread.currentThread().getName() + "被唤醒...");
                monitor.notifyAll();
            }
        }

        public static void interrupt(Thread thread){
            thread.interrupt();
        }

        @Override
        public void run() {
            synchronized (monitor){
                System.out.println("Thread:" + Thread.currentThread().getName() + "获取同步对象...");

                try {
                    monitor.wait();
                } catch (InterruptedException e) {
                    System.out.println("Thread:" + Thread.currentThread().getName() + " wait的时候被中断了");
                }
            }
        }
    }
}
